extends Node3D

const BOARD_WIDTH = 21
const BOARD_HEIGHT = 12
const TILE_SIZE = 2.0
const TILE_HEIGHT = 0.05
const TILE_GAP = 0.05  # Small gap between tiles for visual clarity

var grid_tiles = []
var occupied_tiles = {}

@onready var grid_container = $GridContainer
@onready var tile_mesh_template = $TileMesh
@onready var camera_controller = get_node("/root/Main/CameraController")

var tile_materials = {
	"default": preload("res://materials/tile_default.tres"),
	"player": preload("res://materials/tile_player.tres"),
	"enemy": preload("res://materials/tile_enemy.tres"),
	"hover": preload("res://materials/tile_hover.tres")
}

func _ready():
	create_board()
	if not tile_materials["default"]:
		create_default_materials()

func create_default_materials():
	var default_mat = StandardMaterial3D.new()
	default_mat.albedo_color = Color(0.85, 0.85, 0.85, 1)
	default_mat.roughness = 0.7
	default_mat.metallic = 0.1
	tile_materials["default"] = default_mat
	
	var player_mat = StandardMaterial3D.new()
	player_mat.albedo_color = Color(0.3, 0.5, 0.8, 1)
	player_mat.roughness = 0.7
	player_mat.metallic = 0.2
	player_mat.emission_enabled = true
	player_mat.emission = Color(0.3, 0.5, 0.8)
	player_mat.emission_energy = 0.1
	tile_materials["player"] = player_mat
	
	var enemy_mat = StandardMaterial3D.new()
	enemy_mat.albedo_color = Color(0.8, 0.3, 0.3, 1)
	enemy_mat.roughness = 0.7
	enemy_mat.metallic = 0.2
	enemy_mat.emission_enabled = true
	enemy_mat.emission = Color(0.8, 0.3, 0.3)
	enemy_mat.emission_energy = 0.1
	tile_materials["enemy"] = enemy_mat
	
	var hover_mat = StandardMaterial3D.new()
	hover_mat.albedo_color = Color(0.9, 0.9, 0.3, 1)
	hover_mat.roughness = 0.7
	hover_mat.emission_enabled = true
	hover_mat.emission = Color(0.9, 0.9, 0.3)
	hover_mat.emission_energy = 0.3
	tile_materials["hover"] = hover_mat

func create_board():
	var board_offset_x = (BOARD_WIDTH - 1) * (TILE_SIZE + TILE_GAP) / 2.0
	var board_offset_z = (BOARD_HEIGHT - 1) * (TILE_SIZE + TILE_GAP) / 2.0
	
	# Create ground plane under the tiles
	var ground = $Ground
	if ground:
		ground.mesh.size = Vector2(BOARD_WIDTH * (TILE_SIZE + TILE_GAP) + 2, BOARD_HEIGHT * (TILE_SIZE + TILE_GAP) + 2)
	
	for x in range(BOARD_WIDTH):
		grid_tiles.append([])
		for z in range(BOARD_HEIGHT):
			var tile = create_tile(x, z)
			tile.position = Vector3(
				x * (TILE_SIZE + TILE_GAP) - board_offset_x,
				TILE_HEIGHT / 2,
				z * (TILE_SIZE + TILE_GAP) - board_offset_z
			)
			grid_container.add_child(tile)
			grid_tiles[x].append(tile)
			
			# Color coding for different zones
			if z < 4:  # Bottom 4 rows - player zone
				set_tile_material(tile, "player")
			elif z >= BOARD_HEIGHT - 4:  # Top 4 rows - enemy zone
				set_tile_material(tile, "enemy")
			else:  # Middle rows - neutral zone
				set_tile_material(tile, "default")

func create_tile(x: int, z: int) -> MeshInstance3D:
	var tile = MeshInstance3D.new()
	
	# Create a box mesh for the tile
	var box_mesh = BoxMesh.new()
	box_mesh.size = Vector3(TILE_SIZE - TILE_GAP, TILE_HEIGHT, TILE_SIZE - TILE_GAP)
	tile.mesh = box_mesh
	
	tile.set_meta("grid_x", x)
	tile.set_meta("grid_z", z)
	
	# Add collision for mouse detection
	var static_body = StaticBody3D.new()
	var collision_shape = CollisionShape3D.new()
	var box_shape = BoxShape3D.new()
	box_shape.size = Vector3(TILE_SIZE - TILE_GAP, TILE_HEIGHT, TILE_SIZE - TILE_GAP)
	collision_shape.shape = box_shape
	
	static_body.add_child(collision_shape)
	tile.add_child(static_body)
	
	# Add subtle border effect
	var border = MeshInstance3D.new()
	var border_mesh = BoxMesh.new()
	border_mesh.size = Vector3(TILE_SIZE - TILE_GAP * 2, TILE_HEIGHT * 0.8, TILE_SIZE - TILE_GAP * 2)
	border.mesh = border_mesh
	border.position.y = TILE_HEIGHT * 0.1
	
	var border_mat = StandardMaterial3D.new()
	border_mat.albedo_color = Color(0.2, 0.2, 0.2, 0.3)
	border_mat.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
	border.set_surface_override_material(0, border_mat)
	tile.add_child(border)
	
	return tile

func set_tile_material(tile: MeshInstance3D, material_type: String):
	if tile and tile.mesh and tile_materials.has(material_type):
		tile.set_surface_override_material(0, tile_materials[material_type])

func get_tile_at_position(world_pos: Vector3) -> Vector2i:
	var board_offset_x = (BOARD_WIDTH - 1) * (TILE_SIZE + TILE_GAP) / 2.0
	var board_offset_z = (BOARD_HEIGHT - 1) * (TILE_SIZE + TILE_GAP) / 2.0
	
	var x = int((world_pos.x + board_offset_x) / (TILE_SIZE + TILE_GAP) + 0.5)
	var z = int((world_pos.z + board_offset_z) / (TILE_SIZE + TILE_GAP) + 0.5)
	
	x = clamp(x, 0, BOARD_WIDTH - 1)
	z = clamp(z, 0, BOARD_HEIGHT - 1)
	
	return Vector2i(x, z)

func get_tile_world_position(x: int, z: int) -> Vector3:
	var board_offset_x = (BOARD_WIDTH - 1) * (TILE_SIZE + TILE_GAP) / 2.0
	var board_offset_z = (BOARD_HEIGHT - 1) * (TILE_SIZE + TILE_GAP) / 2.0
	return Vector3(
		x * (TILE_SIZE + TILE_GAP) - board_offset_x,
		TILE_HEIGHT,
		z * (TILE_SIZE + TILE_GAP) - board_offset_z
	)

func is_tile_occupied(x: int, z: int) -> bool:
	var key = str(x) + "," + str(z)
	return occupied_tiles.has(key)

func set_tile_occupied(x: int, z: int, occupied: bool):
	var key = str(x) + "," + str(z)
	if occupied:
		occupied_tiles[key] = true
	else:
		occupied_tiles.erase(key)

func is_player_zone(z: int) -> bool:
	return z < 4  # Bottom 4 rows for player

func is_enemy_zone(z: int) -> bool:
	return z >= BOARD_HEIGHT - 4  # Top 4 rows for enemy

func highlight_tile(x: int, z: int):
	if x >= 0 and x < BOARD_WIDTH and z >= 0 and z < BOARD_HEIGHT:
		set_tile_material(grid_tiles[x][z], "hover")

func unhighlight_tile(x: int, z: int):
	if x >= 0 and x < BOARD_WIDTH and z >= 0 and z < BOARD_HEIGHT:
		if is_player_zone(z):
			set_tile_material(grid_tiles[x][z], "player")
		elif is_enemy_zone(z):
			set_tile_material(grid_tiles[x][z], "enemy")
		else:
			set_tile_material(grid_tiles[x][z], "default")